package cn.edu.nju.newsFeed;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.edu.nju.R;
import cn.edu.nju.sharing.StartUpActivity;
import cn.edu.nju.storage.StoreDataProvider;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Log;
import android.widget.Toast;

public class NewsFeedProvider {
	private static NewsFeedProvider provider;
	private List<NewsFeedItem> items;
	private Activity activity;

	private String serverUrl;

	public static NewsFeedProvider getInstance(Activity activity) {
		if (provider == null) {
			provider = new NewsFeedProvider(activity);
		}
		return provider;
	}

	private NewsFeedProvider(Activity activity) {
		this.activity = activity;
		serverUrl = activity.getString(R.string.server_url) + "news.php";
	}

	public List<NewsFeedItem> getNewsFeedItems(){
		return items;
	}
	
	public void refresh() {
		items = new ArrayList<NewsFeedItem>();
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			
			entity.addPart("id", new StringBody( "" + StoreDataProvider.getInstance(activity).getUserId()));
			entity.addPart("latitude", new StringBody("" + StartUpActivity.latitude));
			entity.addPart("longitude",new StringBody("" + StartUpActivity.longitude));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();
			
			if (context == "none") {
				return;
			} else {
				JSONArray jsonArray = new JSONArray(context);
				items = new ArrayList<NewsFeedItem>();

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					long postUserId = object.getInt("owner_id");
					long postId = object.getInt("id");
					Bitmap avatar = getAvatar(postUserId);
					String postUserName = object.getString("postUserName");
					String postContent = object.getString("content_text");
					if(postId == 56){
						Toast.makeText(activity, postContent, 100000).show();
					}
					String time = object.getString("time_release");
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					Date date = dateFormat.parse(time);
					
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date);
					
					Bitmap previewImage = getPreviewImage(postId);

					int imageNumber = getImageNumber(postId);
					int likeNumber = object.getInt("num_like");
					int commentsNumber = getCommentsNumber(postId);

					items.add(new NewsFeedItem(postUserId, postId, avatar,
							postUserName, postContent, calendar, previewImage,
							imageNumber, likeNumber, commentsNumber, activity));
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Bitmap getAvatar(long user_id) {
		try {
			String url = activity.getString(R.string.server_url) + "avatar.php";
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(url);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + user_id));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();

			return BitmapFactory.decodeStream(input);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private Bitmap getPreviewImage(long news_id) {
		try {
			String url = activity.getString(R.string.server_url) + "image.php";
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(url);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + news_id));
			entity.addPart("option", new StringBody("preview"));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();

			Bitmap bitmap = BitmapFactory.decodeStream(input);
			int width = bitmap.getWidth();
			int height = bitmap.getHeight();

			float scaleWidth = (float) 100.0 / width;
			float scaleHeight = (float) 100.0 / height;

			Matrix matrix = new Matrix();
			matrix.postScale(scaleWidth, scaleHeight);
			matrix.postRotate(0);

			return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
					true);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private int getImageNumber(long news_id) {
		try {
			String url = activity.getString(R.string.server_url) + "image.php";
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(url);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + news_id));
			entity.addPart("option", new StringBody("number"));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));
			int number = Integer.parseInt(reader.readLine());
			reader.close();
			return number;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	private int getCommentsNumber(long news_id) {
		try {
			String url = activity.getString(R.string.server_url)
					+ "comments.php";
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(url);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + news_id));
			entity.addPart("option", new StringBody("num_comment"));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));
			String content = reader.readLine();
			reader.close();
			
			return Integer.parseInt(content);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public NewsFeedItem getNewsFeedItem(int index) {
		return items.get(index);
	}
}
